<template>
    <div style="margin-left: 50px">
        <div style="display: flex">
            <span style="font-size: 25px">{{ $t('file.management') }}</span>

            <div style="margin-left: 5px;margin-right: 5px">
                <el-input placeholder="请输入关键字，如有多条件用，隔开" v-model="searchInfo" style="width: 200px"></el-input>
                <el-button style="margin-left: 5px" type="success" @click="searchFileInfo">
                    <el-icon>
                        <Search/>
                    </el-icon>
                </el-button>
            </div>
            <el-upload :http-request="updateFile" :show-file-list="false"></el-upload>
        </div>
        <el-table
            style="width: 1200px"
            :data="state.fileList"
            :default-sort="[{ prop: 'fileName', order: 'fileName' },{ prop: 'registerDate', order: 'descending' }]"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="30"/>
            <el-table-column prop="fileName" sortable label="文件名"/>
            <el-table-column prop="filePackage" label="文件夹"/>
            <el-table-column prop="fileCapacity" label="大小"/>
            <el-table-column prop="creationTime" label="创建时间"/>
            <el-table-column label="操作" width="300">
                <template #default="scope">
                    <el-dropdown>
                        <template #dropdown>
                            下载
                        </template>
                        <el-toolTip content="下载" placement="bottom" effect="light">
                            <el-button type="primary" size="small" style="margin-right: 10px"
                                       @click="downloadFile(scope.row)">
                                <el-icon>
                                    <Download/>
                                </el-icon>
                                <!--              下载-->
                            </el-button>
                        </el-toolTip>
                    </el-dropdown>
                    <el-dropdown>
                        <template #dropdown>
                            分享
                        </template>
                        <el-toolTip content="分享" placement="bottom" effect="light">
                            <el-button type="primary" size="small" @click="openShareFilesDialog(scope.row)"
                                       style="margin-right: 10px">
                                <el-icon>
                                    <Position/>
                                </el-icon>
                                <!--            分享-->
                            </el-button>
                        </el-toolTip>
                    </el-dropdown>
                    <el-dropdown>
                        <template #dropdown>
                            收藏
                        </template>
                        <el-toolTip content="收藏" placement="bottom" effect="light">
                            <el-button type="primary" size="small" @click="collectionFileInfo(scope.row)"
                                       style="margin-right: 10px">
                                <el-icon>
                                    <Star/>
                                </el-icon>
                                <!--            收藏-->
                            </el-button>
                        </el-toolTip>
                    </el-dropdown>
                    <el-dropdown>
                        <template #dropdown>
                            删除
                        </template>
                        <el-toolTip content="删除" placement="bottom" effect="light">
                            <el-button type="primary" size="small" @click="deleteFileInfo(scope.row)"
                                       style="margin-right: 10px">
                                <el-icon>
                                    <Delete/>
                                </el-icon>
                                <!--            删除-->
                            </el-button>
                        </el-toolTip>
                    </el-dropdown>
                    <el-dropdown>
                        <template #dropdown>
                            预览
                        </template>
                        <el-toolTip content="预览" placement="bottom" effect="light">
                            <el-button v-if="previewList.includes(scope.row.fileName.split('.')[1])" type="primary"
                                       size="small" @click="openPreviewDialog(scope.row)"
                                       style="margin-right: 10px">
                                <el-icon>
                                    <Sunny/>
                                </el-icon>
                                <!--            预览-->
                            </el-button>
                        </el-toolTip>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 10px">
            <el-pagination
                v-model:currentPage="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total=total
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"/>
        </div>
        <el-dialog
            v-model="shareFilesDialog"
            title="分享文件"
            width="20%"
        >
            <span>邮箱</span>
            <el-input v-model="state.sendEmail" style="width:200px;margin-left: 10px"></el-input>
            <template #footer>
      <span class="dialog-footer">

        <el-button type="primary" @click="shareFilesInfo">
         确认
        </el-button>
      </span>
            </template>
        </el-dialog>
        <el-dialog
            v-model="previewDialog"
            title="预览"
            width="36%"
        >
            <div>
                <el-image style="width: 475px; height: 500px" :src="state.openImgUrl"/>
            </div>
            <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="previewDialog = false">确认</el-button>
      </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref, watch} from "vue";
import {Plus, Position, Download, Star, Delete, Search, Sunny} from "@element-plus/icons-vue"
import request from "../request"
import ElNotification, {ElMessage} from "element-plus";
import COS from 'cos-js-sdk-v5'

const state = reactive({
    fileList: [],
    shareFileUrl: '',
    fileInfo: {},
    sendEmail: "",
    openImgUrl: '',
    openTxtUrl: '',
})


// 默认初始位置
const currentPage = ref(1)
// 默认每页个数
const pageSize = ref(10)
const searchInfo = ref('')
const total = ref(10)
const shareFilesDialog = ref(false)
const previewDialog = ref(false)
const previewList = ['png', 'jpg', 'PNG', 'JPG']
onMounted(() => {
    searchFileInfo()
})

const handleSizeChange = (val) => {
    pageSize.value = val
    searchFileInfo()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    searchFileInfo()
}
const searchFileInfo = () => {
    request.get('file/queryAllFileInfoList', {
        params: {
            currentPage: currentPage.value,
            pageSize: pageSize.value,
            searchInfo: searchInfo.value,
        }
    }).then(res => {
        if (res.success) {
            state.fileList = res.data.data
            for (let i of state.fileList) {
                i.fileCapacity = sizeTostr(parseInt(i.fileCapacity))
            }
            total.value = res.data.total
        } else {
            ElNotification.error(res.msg)
        }
    })
}
const openPreviewDialog = (fileInfo) => {
    state.openImgUrl = fileInfo.filePath
    previewDialog.value = true
}

const sizeTostr = (size) => {

    console.info(size)
    let data = "";
    if (size < 0.1 * 1024) { //如果小于0.1KB转化成B
        data = size.toFixed(2) + "B";
    } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
        data = (size / 1024).toFixed(2) + "KB";
    } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
    } else { //其他转化成GB
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }
    let sizestr = data + "";
    let len = sizestr.indexOf("\\.");
    let dec = sizestr.substr(len + 1, 2);
    if (dec == "00") {
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
    }
    return sizestr;
}
const handleSelectionChange = () => {

}
//文件下载
const downloadFile = (fileInfo) => {
    request.get('file/getTencentCosInfo', {timeout: 10000}).then(res => {
        if (res.success) {
            const tencentCos = res.data
            const cos = new COS({
                SecretId: tencentCos.secretId,
                SecretKey: tencentCos.secretKey,
            })
            const pathArr = fileInfo.filePath.split('/')
            const filepath = 'file/' + pathArr[pathArr.length - 1]
            cos.getObjectUrl({
                Bucket: tencentCos.bucket,
                Region: tencentCos.region,     /* 存储桶所在地域，必须字段 */
                Key: filepath,
                Sign: true
            }, function (err, data) {
                if (err) {
                    return console.log(err)
                }
                const downloadUrl = data.Url + (data.Url.indexOf('?') > -1 ? '&' : '?') + 'response-content-disposition=attachment'; // 补充强制下载的参数
                window.open(downloadUrl); // 这里是新窗口打开 url，如果需要在当前窗口打开，可以使用隐藏的 iframe 下载，或使用 a 标签 download 属性协助下载
            })
        }
    })
}
// 分享文件对话框
const openShareFilesDialog = (file) => {
    state.shareFileUrl = file.filePath;
    state.fileInfo = file
    shareFilesDialog.value = true;
}
const shareFilesInfo = () => {
    if (state.sendEmail == '' || state.sendEmail == null) {
        ElMessage.warning("请输入邮箱")
        return
    }
    const regEmail = /^([a-zA-Z]|[0-9])(\w|\\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
    if(!regEmail.test(state.sendEmail)){
        ElMessage.warning("请输入正确的邮箱")
        return
    }
    request.post('file/shareFilesInfo', {
        descEmail: state.sendEmail,
        sendShareUuid: state.fileInfo.fileUuid,
        filePath: state.fileInfo.filePath
    }).then(res => {
        if (res.success) {
            ElMessage.success(res.msg)
            shareFilesDialog.value = false;
            searchFileInfo()
        }
    })
}
// 文件上传
const updateFile = (file) => {
    const formData = new FormData()
    formData.append('file', file.file)

    const config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        timeout: 10000
    };
    request.post('file/updateFile', formData, config).then(res => {
        if (res.success) {
            ElMessage.success(res.msg)
            searchFileInfo()
        }
    })
}

//文件删除
const deleteFileInfo = (file) => {
    request.post('file/deleteFileInfo', file).then(res => {
        if (res.success) {
            ElMessage.success(res.msg)
            searchFileInfo()
        }
    })
}
// 文件收藏
const collectionFileInfo = (file) => {
    request.post('file/collectionFileInfo', file).then(res => {
        if (res.success) {
            ElMessage.success(res.msg)
            searchFileInfo()
        }
    })
}
const downloadFiles = (data) => {
    request.get('file/getTencentCosInfo', {timeout: 10000}).then(res => {
        if (res.success) {
            const tencentCos = res.data
            const cos = new COS({
                SecretId: tencentCos.secretId,
                SecretKey: tencentCos.secretKey,
            })
            const key = 'file/' + data.fileName;
            cos.getObjectUrl({
                Bucket: tencentCos.bucket,
                Region: tencentCos.region,     /* 存储桶所在地域，必须字段 */
                Key: key,
                Sign: true
            }, function (err, data) {
                if (err) {
                    return console.log(err)
                }
                const downloadUrl = data.Url + (data.Url.indexOf('?') > -1 ? '&' : '?') + 'response-content-disposition=attachment'; // 补充强制下载的参数
                window.open(downloadUrl); // 这里是新窗口打开 url，如果需要在当前窗口打开，可以使用隐藏的 iframe 下载，或使用 a 标签 download 属性协助下载
            })
        }
    })
}
</script>
